<script setup>
import { userUpdateUserPassword } from '@/api/user'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import {ref} from 'vue'
import { useRouter } from 'vue-router'
const form = ref({
  oldpassword:'',
  newpassword:'',
  checkedpassword:''
})
//校验新密码的逻辑
const checkOldSame = (rule,value, callback) => {
  if (value === form.value.oldpassword) {
    callback(new Error('原密码和新密码不能一样!'))
  } else {
    callback()
  }
}

const checkNewSame = (rule, value, callback) => {
  if (value !== form.value.newpassword) {
    callback(new Error('新密码和确认再次输入的新密码不一样!'))
  } else {
    callback()
  }
}
const rules = ref({
  oldpassword:[
    {required:true,message:'请输入原密码',trigger:'blur'},
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    }
  ],
  newpassword:[
    {required:true,message:'请输入新密码',trigger:'blur'},
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    },
    { validator: checkOldSame, trigger: 'blur' }
  ],
  checkedpassword:[
    {required:true,message:'请再次输入密码',trigger:'blur'},
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    },
    { validator: checkNewSame, trigger: 'blur' }
  ]
})
const formRef = ref()
const userStore = useUserStore()
const router = useRouter()
const submitForm = async ()=>{
  await formRef.value.validate()
  const res = await userUpdateUserPassword(
    {old_pwd:form.value.oldpassword,new_pwd:form.value.newpassword,re_pwd:form.value.checkedpassword})
  ElMessage.success(res.data.message)
  userStore.setToken('')
  userStore.setUserInfo({})
  router.push('/login')
}
const resetForm = ()=>{
  formRef.value.resetFields()
}
</script>
<template>
  <page-container title="重置密码">
    <el-row>
      <el-col :span="12">
        <el-form size="large" :rules="rules" :model="form" ref="formRef">
          <el-form-item label="原密码" prop="oldpassword">
            <el-input v-model="form.oldpassword" type="password" show-password>
            </el-input >
          </el-form-item>
          <el-form-item label="新密码" prop="newpassword">
            <el-input v-model="form.newpassword" type="password" show-password>
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkedpassword">
            <el-input v-model="form.checkedpassword" type="password" show-password>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">确认密码</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </page-container>
</template>
